package javango.util;

import java.util.IllegalFormatException;
import java.util.Map;
import java.util.MissingFormatArgumentException;

import org.apache.commons.lang.StringUtils;

public class StringFormat {

	public static String format(String format, Map<String, Object> args) throws IllegalFormatException {
		StringBuilder newFormat = new StringBuilder();
		
		int start = 0;
		int loc = format.indexOf("%(");
		Object[] newArgs = new Object[StringUtils.countMatches(format, "%(")];
		int argCount = 0;
		while (loc != -1) {
			loc++;
			newFormat.append(format.substring(start, loc));
			int end = format.indexOf(")", loc);
			String argName = format.substring(loc+1, end);
			if (!args.containsKey(argName)) {
				throw new MissingFormatArgumentException(argName);
			}
			Object value = args.get(argName);
			newArgs[argCount++] = value;
			start = end+1;
			loc = format.indexOf("%(", start);
		}
		newFormat.append(format.substring(start));
		return String.format(newFormat.toString(), newArgs);
	}
		

}
